#!/usr/bin/env python3
"""
分析GitHub和Copilot请求的脚本，提供详细统计信息
"""

import re
import os
from collections import defaultdict, Counter
from datetime import datetime

def analyze_requests(file_path):
    """分析GitHub和Copilot请求"""
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 统计信息
        stats = {
            'total_requests': 0,
            'domains': Counter(),
            'methods': Counter(),
            'endpoints': Counter(),
            'copilot_versions': set(),
            'editor_versions': set(),
            'api_versions': set()
        }
        
        # 按交互分割
        interactions = re.split(r'={80,}\n交互 #\d+', content)
        
        request_details = []
        
        for interaction in interactions[1:]:  # 跳过文件头
            if not interaction.strip():
                continue
                
            stats['total_requests'] += 1
            
            # 提取URL
            url_match = re.search(r'URL: (https?://[^\s]+)', interaction)
            if url_match:
                url = url_match.group(1)
                
                # 提取域名
                domain_match = re.search(r'https?://([^/]+)', url)
                if domain_match:
                    domain = domain_match.group(1)
                    stats['domains'][domain] += 1
                
                # 提取路径作为端点
                path_match = re.search(r'https?://[^/]+(/[^\s?]*)', url)
                if path_match:
                    endpoint = path_match.group(1)
                    stats['endpoints'][endpoint] += 1
            
            # 提取请求方法
            method_match = re.search(r'请求方法: (\w+)', interaction)
            if method_match:
                method = method_match.group(1)
                stats['methods'][method] += 1
            
            # 提取版本信息
            copilot_version_match = re.search(r'copilot-language-server-version: ([^\n]+)', interaction)
            if copilot_version_match:
                stats['copilot_versions'].add(copilot_version_match.group(1))
            
            editor_version_match = re.search(r'editor-plugin-version: ([^\n]+)', interaction)
            if editor_version_match:
                stats['editor_versions'].add(editor_version_match.group(1))
            
            api_version_match = re.search(r'x-github-api-version: ([^\n]+)', interaction)
            if api_version_match:
                stats['api_versions'].add(api_version_match.group(1))
            
            # 收集请求详情
            time_match = re.search(r'时间: ([^\n]+)', interaction)
            request_detail = {
                'url': url if url_match else 'Unknown',
                'method': method if method_match else 'Unknown',
                'time': time_match.group(1) if time_match else 'Unknown'
            }
            request_details.append(request_detail)
        
        return stats, request_details
        
    except Exception as e:
        print(f"❌ 分析失败: {e}")
        return None, None

def print_analysis(stats, request_details):
    """打印分析结果"""
    
    print("=" * 80)
    print("📊 GitHub & Copilot 请求分析报告")
    print("=" * 80)
    
    print(f"\n📈 总体统计:")
    print(f"   总请求数: {stats['total_requests']}")
    
    print(f"\n🌐 域名分布:")
    for domain, count in stats['domains'].most_common():
        percentage = (count / stats['total_requests']) * 100
        print(f"   {domain}: {count} 次 ({percentage:.1f}%)")
    
    print(f"\n🔧 请求方法分布:")
    for method, count in stats['methods'].most_common():
        percentage = (count / stats['total_requests']) * 100
        print(f"   {method}: {count} 次 ({percentage:.1f}%)")
    
    print(f"\n🎯 热门端点 (Top 10):")
    for endpoint, count in stats['endpoints'].most_common(10):
        percentage = (count / stats['total_requests']) * 100
        print(f"   {endpoint}: {count} 次 ({percentage:.1f}%)")
    
    print(f"\n🔧 Copilot版本:")
    for version in sorted(stats['copilot_versions']):
        print(f"   {version}")
    
    print(f"\n💻 编辑器插件版本:")
    for version in sorted(stats['editor_versions']):
        print(f"   {version}")
    
    print(f"\n🔗 GitHub API版本:")
    for version in sorted(stats['api_versions']):
        print(f"   {version}")
    
    # 按服务类型分类
    print(f"\n📋 按服务类型分类:")
    copilot_api_count = sum(1 for detail in request_details if 'api.individual.githubcopilot.com' in detail['url'])
    github_api_count = sum(1 for detail in request_details if 'api.github.com' in detail['url'])
    telemetry_count = sum(1 for detail in request_details if 'telemetry' in detail['url'])
    avatar_count = sum(1 for detail in request_details if 'avatars.githubusercontent.com' in detail['url'])
    
    print(f"   🤖 Copilot API: {copilot_api_count} 次")
    print(f"   🐙 GitHub API: {github_api_count} 次")
    print(f"   📊 遥测服务: {telemetry_count} 次")
    print(f"   👤 头像服务: {avatar_count} 次")
    print(f"   🔗 其他: {stats['total_requests'] - copilot_api_count - github_api_count - telemetry_count - avatar_count} 次")

def main():
    """主函数"""
    file_path = "github_copilot_requests.txt"
    
    if not os.path.exists(file_path):
        print(f"❌ 筛选结果文件不存在: {file_path}")
        print("请先运行筛选脚本生成GitHub/Copilot请求记录")
        return
    
    print("🔍 开始分析GitHub和Copilot请求...")
    
    stats, request_details = analyze_requests(file_path)
    
    if stats and request_details:
        print_analysis(stats, request_details)
        
        # 保存分析报告（当前目录）
        report_file = "github_copilot_analysis.txt"
        
        # 将分析结果写入文件
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write("GitHub & Copilot 请求分析报告\n")
            f.write("=" * 50 + "\n")
            f.write(f"分析时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"数据源: {file_path}\n")
            f.write(f"总请求数: {stats['total_requests']}\n\n")
            
            f.write("域名分布:\n")
            for domain, count in stats['domains'].most_common():
                percentage = (count / stats['total_requests']) * 100
                f.write(f"  {domain}: {count} ({percentage:.1f}%)\n")
            
            f.write(f"\n请求详情:\n")
            for i, detail in enumerate(request_details, 1):
                f.write(f"{i}. {detail['time']} - {detail['method']} {detail['url']}\n")
        
        print(f"\n📁 分析报告已保存到: {os.path.abspath(report_file)}")
    else:
        print("❌ 分析失败")

if __name__ == "__main__":
    main()